#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库迁移脚本：为questions表添加explanation和wrong_analysis字段
"""

import sqlite3
import os
from pathlib import Path

def migrate_database():
    """为questions表添加新字段"""
    # 获取数据库文件路径
    db_path = Path(__file__).parent / "questions.db"
    
    if not db_path.exists():
        print(f"数据库文件不存在: {db_path}")
        return False
    
    try:
        # 连接数据库
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 检查字段是否已存在
        cursor.execute("PRAGMA table_info(questions)")
        columns = [column[1] for column in cursor.fetchall()]
        
        # 添加explanation字段
        if 'explanation' not in columns:
            cursor.execute("ALTER TABLE questions ADD COLUMN explanation TEXT")
            print("✅ 已添加explanation字段")
        else:
            print("ℹ️ explanation字段已存在")
        
        # 添加wrong_analysis字段
        if 'wrong_analysis' not in columns:
            cursor.execute("ALTER TABLE questions ADD COLUMN wrong_analysis TEXT")
            print("✅ 已添加wrong_analysis字段")
        else:
            print("ℹ️ wrong_analysis字段已存在")
        
        # 提交更改
        conn.commit()
        print("🎉 数据库迁移完成！")
        
        return True
        
    except Exception as e:
        print(f"❌ 迁移失败: {e}")
        return False
    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    print("开始数据库迁移...")
    success = migrate_database()
    if success:
        print("数据库迁移成功完成！")
    else:
        print("数据库迁移失败！")